import { defineStore } from 'pinia'
import {
  accountLoginRequest,
  getUserInforById,
  getUserMenusByRoleId
} from '@/service/login/login'
import { LoginForm } from '@/types'
import { localCache } from '@/utils/cache'
import router from '@/router'
import { LOGIN_TOKEN } from '@/global/constans'
import activeRoutes from '@/utils/activeRoutes'
import { useMainStore } from '../main/main'
interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
}

export const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: localCache.getCache(LOGIN_TOKEN) ?? '',
    userInfo: {},
    userMenus: []
  }),
  actions: {
    // promise写法
    // loginAccountAction(data: LoginForm) {
    //   accountLoginRequest(data)
    //     .then((res) => {
    //       this.id = res.data.id
    //       this.token = res.data.token
    //       this.name = res.data.name
    //       localCache.setCache(LOGIN_TOKEN, this.token)
    //       router.push('/main')
    //     })
    //     .then(() => {
    //       ElMessage.success('登录成功')
    //     })
    //     .catch(() => {
    //       ElMessage.error('登录失败')
    //     })
    // }
    // async/await写法
    async loginAccountAction(data: LoginForm) {
      // 1.登录接口
      const loginResult = await accountLoginRequest(data)

      // 问题出在这行代码。如果登录失败，这时候data当中没有token，所以这时state里面的token会变成undefined。
      // 而这时候进行token的本地存储在不做判断的情况下就会报错
      const token = loginResult.data.token

      // 2.进行本地存储token
      if (token) {
        this.token = token
        const id = loginResult.data.id
        localCache.setCache(LOGIN_TOKEN, this.token)
        // 3.获取用户详细信息并存入本地
        const userInfoResult = await getUserInforById(id)
        const userInfo = userInfoResult.data
        if (userInfo) {
          this.userInfo = userInfo
          localCache.setCache('userInfo', userInfo)
        }

        // 根据角色来展示菜单，获取菜单并存储
        const userMenusResult = await getUserMenusByRoleId(id)
        const userMenus = userMenusResult.data
        if (userMenus) {
          this.userMenus = userMenus
          localCache.setCache('userMenus', userMenus)
        } else {
          this.userMenus = []
          localCache.removeCache('userMenus')
        }

        // 请求所有roles和departments
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        //动态添加路由
        const routes = activeRoutes(this.userMenus)
        routes.forEach((route: any) => {
          router.addRoute('main', route)
        })

        // 3.进行页面跳转
        router.push('/main')
      }
    },
    // 用户刷新默认加载数据
    loadLocalCacheAction() {
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')

      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 请求所有roles和departments
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        const routes = activeRoutes(this.userMenus)
        routes.forEach((route: any) => {
          router.addRoute('main', route)
        })
      }
    }
  }
})
